package com.syl.upimg.service.impl;

import com.syl.upimg.bean.XiaoMiBean;
import com.syl.upimg.enums.ImageUploadTypeEnum;
import com.syl.upimg.service.BaseUpload;
import com.syl.upimg.utils.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 小米有品羊毛 速度最慢
 *
 * @author syl
 **/
@Service
public class XiaoMiFleece implements BaseUpload {
    @Autowired
    private RestTemplate restTemplate;

    @Override
    public RestTemplate createRestTemplate() {
        return restTemplate;
    }

    @Override
    public LinkedMultiValueMap<String, Object> getParam(FileSystemResource file, String fileName, String fileType) {
        LinkedMultiValueMap<String, Object> linkedMultiValueMap = new LinkedMultiValueMap<>();
        linkedMultiValueMap.add("pic", file);
        return linkedMultiValueMap;
    }

    @Override
    public HttpHeaders getDefaultHeader() {
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.add("User-Agent", "MJYP/2.6.1 (iPhone; iOS 12.1; Scale/2.00)");
        return httpHeaders;
    }

    @Override
    public String[] getLimit() {
        return new String[]{"jpg", "png"};
    }

    @Override
    public String getUrl() {
        return "https://shopapi.io.mi.com/homemanage/shop/uploadpic";
    }

    public XiaoMiBean upload(String filePath) throws IOException {
        return this.upload(filePath, false);
    }

    public XiaoMiBean upload(String filePath, boolean delete) throws IOException {
        XiaoMiBean xiaoMiBean = this.upload(filePath, XiaoMiBean.class, delete);
        String result = xiaoMiBean.getResult();
        if (StringUtils.isEmpty(result)) return null;
        String temp = RegexUtils.removeAll(result, "[&=]");
        if (StringUtils.isEmpty(result)) return null;
        String url = RegexUtils.removeAll(result, "&w.+");
        String extract = RegexUtils.extract(temp, "\\d+h\\d+");
        String[] split = extract.split("h");
        xiaoMiBean.setImageUrl(url);
        xiaoMiBean.setBaseUrl(url);
        xiaoMiBean.setWidth(Integer.valueOf(split[0]));
        xiaoMiBean.setHeight(Integer.valueOf(split[1]));
        xiaoMiBean.setImageUploadTypeEnum(ImageUploadTypeEnum.MI);
        return xiaoMiBean;
    }

}
